<template>
  <div class="main coupon-edit">
    <section>
      <el-form ref="form" size="medium" label-width="150px" :rules="commonRules" :model="configData">
        <div class="block-header"><div>设置礼包配置</div></div>
        <div class="block-content">
          <el-form-item label="礼包名称:" prop="boxBonusGift.name" :rules="commonRules.notNullRule">
            <el-input v-model="configData.boxBonusGift.name" :disabled="type===2||type ===0" clearable></el-input>
          </el-form-item>
          <el-form-item label="礼包标题:" prop="boxBonusGift.title" :rules="commonRules.notNullRule">
            <el-input v-model="configData.boxBonusGift.title" :disabled="type===2||type ===0" maxlength="40" clearable></el-input>
          </el-form-item>
          <el-form-item label="礼包类型:" prop="boxBonusGift.giftType" :rules="commonRules.notNullRule">
            <el-select v-model="configData.boxBonusGift.giftType" :disabled="!!id" clearable>
              <el-option label="不可退" :value="0"></el-option>
              <el-option label="可退" :value="1"></el-option>
              <el-option label="云仓" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="configData.boxBonusGift.giftType===2" label="选择云仓活动:" :rules="commonRules.notNullRule">
            <div v-for="(i, idx) in moreList" :key="idx" class="mt10">
              <el-select v-model="i.seriesName" :disabled="type===2" clearable @change="val => changeActivity(idx, val)">
                <el-option v-for="(item, index) in activityList" :key="index" :label="item.seriesName" :value="{value:item.seriesId,label:item.seriesName}"></el-option>
              </el-select>
              <el-button v-if="idx===0" type="text" @click="addActivity">添加云仓活动</el-button>
              <el-button v-else type="text" @click="delActivity(idx)">移除</el-button>
            </div>
          </el-form-item>
          <el-form-item label="礼包主图：" prop="boxBonusGift.imageMain" :rules="commonRules.notNullRule">
            <el-upload
              class="avatar-uploader"
              accept="image/*"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :disabled="type===2||type ===0"
              :on-success="(res)=>{
                configData.boxBonusGift.imageMain = replaceImgUrl(res.filePath);
              }">
              <img v-if="configData.boxBonusGift.imageMain" :src="configData.boxBonusGift.imageMain" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item label="礼包介绍图片：" prop="boxBonusGift.imageIntroduce" :rules="commonRules.notNullRule">
                        <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :disabled="type===2||type ===0"
                                :on-success="(res)=>{
                            configData.boxBonusGift.imageIntroduce = replaceImgUrl(res.filePath);
                        }">
                            <img v-if="configData.boxBonusGift.imageIntroduce" :src="configData.boxBonusGift.imageIntroduce" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item> -->
          <el-form-item label="礼包介绍图片：" prop="boxBonusGift.imageIntroduceList" :rules="commonRules.notNullRule">
            <ul class="upload-img-list">
              <draggable v-model="configData.boxBonusGift.imageIntroduceList" :options="{group:'imageIntroduceList'}" @start="drag=true" @end="drag=false">
                <li v-for="(imgItem, imgIndex) of configData.boxBonusGift.imageIntroduceList" :key="imgIndex" class="img-preview">
                  <img :src="imgItem" alt="">
                  <div v-if="type===1 || type===3 || type===8" class="img-preview-mask">
                    <div class="mask-btn">
                      <i title="删除" class="el-icon-delete" @click="()=>{configData.boxBonusGift.imageIntroduceList.splice(imgIndex, 1)}"></i>
                    </div>
                  </div>
                </li>
              </draggable>
              <li v-if="type === 1 || type === 3 || type===8">
                <label class="upload-btn">
                  <input type="file" @change="(event)=>{uploadImg(event, configData.boxBonusGift.imageIntroduceList)}" />
                  <i class="el-icon-plus"></i>
                </label>
              </li>
            </ul>
            <div v-if="configData.boxBonusGift.imageIntroduceList.length>1 && (type===1||type===3|| type===8)" style="color: red">拖拽已上传的图片可以进行排序</div>
          </el-form-item>
          <el-form ref="form1" size="medium" label-width="150px" :rules="commonRules" :model="configData" :disabled="type===2||type ===0">
            <el-form-item label="礼包详情页图片：" prop="boxBonusGift.comment" :rules="commonRules.notNullRule">
              <tinymce v-model="configData.boxBonusGift.comment" :height="520"></tinymce>
            </el-form-item>
          </el-form>
          <el-form-item label="有效期:" prop="timeDate" :rules="commonRules.notNullRule">
            <template>
              <el-date-picker
                v-model="configData.timeDate"
                :disabled="type===2"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </template>
          </el-form-item>
          <el-form-item label="起售金额:" prop="boxBonusGift.givingPrice" :rules="commonRules.priceRule">
            <el-input v-model="configData.boxBonusGift.givingPrice" :disabled="type===2||type ===0" clearable>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="赠送权益:" prop="boxBonusGift.givingType" :rules="commonRules.notNullRule">
            <el-select v-model="configData.boxBonusGift.givingType" :disabled="type===2||type===0" clearable>
              <el-option :value="1" label="官方身份"></el-option>
              <el-option :value="0" label="总代身份"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="礼包排序:" prop="boxBonusGift.sort">
            <el-input v-model="configData.boxBonusGift.sort" :disabled="type===2" clearable>
            </el-input><p style="color: red">提示：1、礼包排序0最高，依次递减，默认排序为99999最低，排序相同时根据创建时间排序； 2、此排序控制碧选后台及APP上提货页礼包展示；</p>
          </el-form-item>
          <el-form-item label="选择箱起活动:">
            <div class="add-btn-block">
              <el-button type="primary" size="small" icon="el-icon-circle-plus" plain :disabled="type===2" @click="addBox">添加箱起活动</el-button>
            </div>
          </el-form-item>
        </div>
        <el-table ref="expandTable" :data="configData.boxSeriesDTOs" :default-expand-all="true">
          <el-table-column align="center" type="expand" width="100">
            <template slot-scope="scope">
              <el-table :data="scope.row.boxGoodsDTOS">
                <el-table-column align="center" label="商品名称" prop="goodsName"></el-table-column>
                <el-table-column align="center" label="起卖数量" prop="minnum"></el-table-column>
                <el-table-column align="center" label="箱规（件）" prop="boxCount"></el-table-column>
                <el-table-column align="center" label="普通会员价" prop="ordinaryPrice"></el-table-column>
                <el-table-column align="center" label="大区价" prop="regionPrice"></el-table-column>
                <el-table-column align="center" label="董事价" prop="directorPrice"></el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="活动名称" prop="seriesName" align="center"></el-table-column>
          <el-table-column label="排序" prop="sort" align="center" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sort" placeholder="请输入排序" maxlength="8" style="width: 120px" @input="scope.row.sort=$event.replace(/[^\d]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="60" fixed="right">
            <template slot-scope="scope">
              <a href="javascript: void(0);" class="el-icon-remove" @click="delBoxSeriesDTOs(scope.$index)"></a>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="是否设置加购商品:">
          <el-radio v-model="isAddGoods" label="0" :disabled="type===2">否</el-radio>
          <el-radio v-model="isAddGoods" label="1" :disabled="type===2">是</el-radio>
          <el-button v-if="isAddGoods==='1'" type="primary" size="small" icon="el-icon-circle-plus" style="marginTop:5px" plain :disabled="type===2" @click="chooseGoods">添加商品</el-button>
        </el-form-item>
        <el-table v-if="isAddGoods==='1'" :data="configData.boxAdditionalGoodsList" border highlight-current-row>
          <el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
          <el-table-column align="center" label="商品ID" prop="goodsId"></el-table-column>
          <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
          <el-table-column align="center" label="加购比例">
            <template slot-scope="scope">
              <el-form-item :prop="'boxAdditionalGoodsList.'+scope.$index+'.buyNum'" :rules="commonRules.numberRule" style="display:inline-block;margin:30px 0px 30px -150px;">
                <el-input v-model="scope.row.buyNum" :disabled="type===2" style="width: 70px" />
              </el-form-item>
              <span style="font-weight: bold">:</span>
              <el-form-item :prop="'boxAdditionalGoodsList.'+scope.$index+'.additionalNum'" :rules="commonRules.numberRule" style="display:inline-block;margin:30px 0px 30px -150px;">
                <el-input v-model="scope.row.additionalNum" :disabled="type===2" style="width: 70px" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="加购价格">
            <template slot-scope="scope">
              <el-form-item :prop="'boxAdditionalGoodsList.'+scope.$index+'.price'" :rules="commonRules.priceRuleZeroT" style="display:inline-block;margin:30px 0px 30px -150px;">
                <el-input v-model="scope.row.price" :disabled="type===2" style="width: 120px" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" :disabled="pageType == 'boxGiftBagView'" @click="removeAddGoods(scope.$index,scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="是否上架:" prop="boxBonusGift.upshelf">
          <el-switch
            v-model="configData.boxBonusGift.upshelf"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            :disabled="type===2">
          </el-switch>
        </el-form-item>
        <el-form-item label="" style="margin-top:20px;">
          <el-button v-show="type!==2" type="primary" size="medium" :loading="btnLoading" @click="save">保存</el-button>
          <el-button type="info" size="medium" plain @click="$router.push({ name: 'boxGiftBag' })">{{ type!==2 ? '取消':'返回' }}</el-button>
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import Tinymce from '@/components/Tinymce'
import differenceBy from 'lodash/differenceBy'
export default {
  name: 'BoxGiftbagEdit',
  components: {
    Tinymce,
    draggable
  },
  data() {
    return {
      moreList: [{
        seriesId: '',
        seriesName: ''
      }],
      activityList: [],
      configData: {
        boxSeriesCloudDTOs: [],
        timeDate: [],
        boxBonusGift: {
          activity: '',
          bonusConfigId: '',
          givingPrice: '',
          givingType: 1,
          endTime: '',
          name: '',
          startTime: '',
          comment: '',
          imageIntroduce: '',
          imageIntroduceList: [],
          imageMain: '',
          sort: 0,
          giftType: 0
        },
        boxSeriesDTOs: [],
        boxAdditionalGoodsList: []
      },
      seriesName: '',
      boxSeriesDTOs: [],
      startTime: '',
      endTime: '',
      btnLoading: false,
      id: '',
      type: '',
      isAddGoods: '0',
      pageType: '' //页面类型
    }
  },
  mounted() {
    this.pageType = this.$route.name
    this.type = Number(this.$route.query.type) // 箱起礼包活动状态 0是活动中，1未开始，2是已失效，3已下架
    if (this.id) {
      this.getConfig()
    }
  },
  created() {
    this.getActivity()
  },
  methods: {
    // 新增云仓活动
    addActivity() {
      this.moreList.push({
        seriesName: '',
        seriesId: ''
      })
      this.configData.boxSeriesCloudDTOs.push({
        seriesName: '',
        seriesId: ''
      })
    },
    // 删除云仓活动
    delActivity(index) {
      this.moreList.splice(index, 1)
      this.configData.boxSeriesCloudDTOs.splice(index, 1)
    },
    // select变化增加云仓活动
    changeActivity(index, params) {
      const { value, label } = params
      if (this.configData.boxSeriesCloudDTOs.length > 0) {
        this.configData.boxSeriesCloudDTOs.forEach((item) => {
          if (item.seriesId === value) {
            this.$message.error('已存在相同的云仓活动')
          }
        })
        this.$set(this.configData.boxSeriesCloudDTOs[index], 'seriesId', value)
        this.$set(this.configData.boxSeriesCloudDTOs[index], 'seriesName', label)
      } else {
        this.configData.boxSeriesCloudDTOs.push({
          seriesName: label,
          seriesId: value
        })
      }
    },
    // 获取云仓活动下拉列表
    getActivity() {
      this.request({
        url: '/bsnl-product/box/list/cloudStock',
        method: 'get'
      }).then((res) => {
        if (res.status === 200) {
          this.activityList = res.data
        }
      }).catch(err => {
        console.log(err)
        this.activityList = []
      })
    },
    getConfig() {
      this.request({
        url: '/bsnl-product/box/bonus/gift/detail?bonusGiftId=' + this.id,
        method: 'get'
      }).then((res) => {
        if (res.status === 200) {
          if(res.data.boxAdditionalGoodsList.length){
            this.isAddGoods = '1'
          }
          res.data.boxBonusGift.imageIntroduceList = res.data.boxBonusGift.imageIntroduce.split(',')
          this.configData = {
            ...res.data,
            timeDate: [res.data.boxBonusGift.startTime, res.data.boxBonusGift.endTime]
          }
          if (res.data.boxSeriesCloudDTOs.length === 0) {
            this.moreList = [{
              seriesId: '',
              seriesName: ''
            }]
            this.configData.boxSeriesCloudDTOs = [{
              seriesName: '',
              seriesId: ''
            }]
          } else {
            this.moreList = JSON.parse(JSON.stringify(res.data.boxSeriesCloudDTOs))
          }
        }
      }).catch(err => {
        this.$message.success(err.message)
      })
    },
    addBox() {
      this.boxSeriesDTOs = [...this.configData.boxSeriesDTOs]
      this.boxSeries(this.boxSeriesDTOs, -1, 1, this.configData.boxSeriesDTOs).then(val => {
        this.configData.boxSeriesDTOs = val
      }).catch(err => {
        this.boxSeriesDTOs = []
      })
    },
    delBoxSeriesDTOs(index) {
      if (this.type === 2 || this.type === 0) {
        this.$message.error('活动已开始无法移除')
        return
      } else {
        this.configData.boxSeriesDTOs.splice(index, 1)
      }
    },
     chooseGoods() {
      const goodsChecked = []
      this.configData.boxAdditionalGoodsList.forEach(item => {
          goodsChecked.push({ goodsId: item.goodsId, name: item.name })
      })
      this.goodsChoose({ count: -1 }, goodsChecked).then(val => {
        const goodsList = this.configData.boxAdditionalGoodsList
        const needDelGoods = differenceBy(goodsList, val, 'goodsId')
        const needAddGoods = differenceBy(val, goodsList, 'goodsId')
        const needDelreal = []
        for (var k = 0; k < needDelGoods.length; k++) {
            needDelreal.push(needDelGoods[k])
        }
        for (var i = 0; i < this.configData.boxAdditionalGoodsList.length; i++) {
          for (var j = 0; j < needDelreal.length; j++) {
            if (this.configData.boxAdditionalGoodsList[i].goodsId === needDelreal[j].goodsId) {
              this.configData.boxAdditionalGoodsList.splice(i, 1)
            }
          }
        }
        needAddGoods.forEach((item) => {
          this.configData.boxAdditionalGoodsList.push({
            goodsId: item.goodsId,
            name: item.name
          })
        })
      })
    },
    removeAddGoods(index, item) {
      this.configData.boxAdditionalGoodsList.splice(index, 1)
    },
    isRepeat(arr) {
      const hash = {}
      for (const i in arr) {
        if (hash[arr[i].seriesId]) {
          return true
        }
        hash[arr[i].seriesId] = true
      }
      return false
    },
    save() {
      if (this.configData.boxSeriesCloudDTOs.length < 1 && this.configData.boxBonusGift.giftType === 2) {
        this.$message.error('请选择云仓活动')
        return false
      }
      const isRepeat = this.isRepeat(this.configData.boxSeriesCloudDTOs)
      if (isRepeat) {
        this.$message.error('已存在相同的云仓活动')
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$refs.form1.validate(valid1 => {
            if (valid1) {
              if (this.configData.boxSeriesDTOs.length < 1) {
                this.$message.error('请添加箱起活动')
                return false
              }
              this.btnLoading = true
              if(this.isAddGoods === '0'){
                this.configData.boxAdditionalGoodsList = []
              }
              this.configData.boxBonusGift.startTime = this.configData.timeDate[0]
              this.configData.boxBonusGift.endTime = this.formatDate(this.configData.timeDate[1], 'YYYY-MM-DD') + ' 23:59:59'
              this.configData.boxBonusGift.imageIntroduce = this.configData.boxBonusGift.imageIntroduceList.join(',')
              const bonusUrl = this.id ? '/bsnl-product/box/bonus/gift/update' : '/bsnl-product/box/bonus/gift/add'
              this.request({
                url: bonusUrl,
                method: 'post',
                data: this.configData
              }).then((res) => {
                if (res.status === 200) {
                  this.$message.success(res.message)
                  this.btnLoading = false
                  this.$router.push({ name: 'boxGiftBag' })
                }
              }).catch((err) => {
                this.btnLoading = false
              })
            }
          })
        }
      })
    },
    toggleRowExpansion(row) {
      this.$refs.expandTable.toggleRowExpansion(row, true)
    },
    uploadImg(event, item) {
      const file = event.target.files[0]
      this.picFileUpload(file, (res) => {
        item.push(this.replaceImgUrl(res.filePath))
      })
    }
  }
}
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .mt10 {
      margin-top: 10px;
    }
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;
        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }

    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin-left: 24px;
    }
    .add-btn-block{
        margin:  0 0 12px 24px;
    }
     .section-content{
         .el-input-group__prepend{
             padding: 0 5px;
         }
        .line{
            text-align: center;
        }
        .el-input{
            width: 100%;
            max-width: 500px;
            min-width: 150px;
        }
        .el-icon-delete{
            color: red;
            font-size: 16px;
            margin: 0 12px;
            cursor: pointer;
        }
        .goods-item{
            padding: 12px 0;
            // border: 1px solid #efefef;
            border-radius: 6px;
            position: relative;

            .avatar-uploader .el-upload,
            .upload-img-list li,
            .upload-img-list .upload-btn{
                width: 120px;
                height: 120px;
                line-height: 118px;
            }
            .upload-img-list .img-preview .img-preview-mask .mask-btn {
                margin-top: 47px;
                line-height: 36px;
                text-align: center;
            }

            .present-item{
                padding: 6px;
                border: 1px solid #efefef;
                margin-bottom: 12px;
                position: relative;

                .el-icon-error{
                    color: red;
                    font-size: 18px;
                    cursor: pointer;
                    top: 12px;
                    right: 12px;
                    position: absolute;
                    z-index: 9;
                }

                &>.el-form-item {
                    margin-bottom: 22px;
                }
                .el-input,
                .el-select{
                    width: 100%;
                    max-width: 160px;
                }
            }
        }
        .add-btn-block{
            margin:  0 0 12px 24px;
        }
        .footer-block{
            text-align: center;
            margin-top: 24px;
        }
    }
</style>
